package com.crealth.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.log4j.Logger;
import com.crealth.db.ClienteleDb;
import com.crealth.db.MyselfClienteleDb;
import com.crealth.db.UserDb;
import com.crealth.memcached.CdrCached;
import com.crealth.model.ClienteleInfoModel;
import com.crealth.model.UserModel;
import com.crealth.utils.StringUtil;

public class ClienteleInfoManager {
	public static Map<Integer, Boolean> groupCallTypeMap = new HashMap<Integer, Boolean>();  //  是否开启  获取制定号码
	
	private static Logger errorLog = Logger.getLogger("error_log");
	private static Logger logger = Logger.getLogger("running_log");
	private static int maxClienteleID = 0;
	private static List<String> allForbidCallee = null;
	private static Random random = new Random();	
	
	public static Boolean getCompanyGroupcallType(int companyID) {
		if ( groupCallTypeMap.containsKey(companyID) ) {
			return groupCallTypeMap.get(companyID);
		} else {
			groupCallTypeMap.put(companyID, true);
			return true;
		}
	}
	
	public static void initMaxID() {
		Integer maxID = ClienteleDb.selectMaxClientID();
		//groupCallType = UserDb.selectGroupCallType();
		if (maxID == null) {
			return ;
		}
		maxClienteleID = maxID;
		logger.info("maxClienteleID: " + maxClienteleID);
		allForbidCallee = ClienteleDb.selectAllForbidCallee();
		if (allForbidCallee != null) {
			logger.info("allForbidCallee number: " + allForbidCallee.size());
		}
	}
	
	public static List<ClienteleInfoModel> getClienteleModel(UserModel user, boolean dialSelfcli) {		
		List<Integer> idls;
		List<ClienteleInfoModel> clienteleInfos = null;
		int userID = user.getId();
		//int companyID = user.getBelongCompanyID();
		//Boolean groupCallType = getCompanyGroupcallType(companyID);
		synchronized (ClienteleInfoManager.class) {
			if (dialSelfcli) {
				clienteleInfos = getMyselfClientleInfo(user);
			}
			if (clienteleInfos == null || clienteleInfos.size() == 0) {
				clienteleInfos = getGroupCallMobiPhone(user);
			}
			if (clienteleInfos == null || clienteleInfos.size() == 0) {
				if (maxClienteleID <= 0) {
					return null;
				}
				int maxId = 0;
				long begID = 0;
				if (maxClienteleID > 100) {
					maxId = maxClienteleID-100;
					begID = random.nextInt(maxId);
				}
				//idls = UserDb.selectAdminIDs();
				idls = new ArrayList<Integer>();
				List<UserModel> branchMgr = UserDb.getBranchCompanyMgr(user.getCompanyID());
				for (UserModel um : branchMgr) {
					idls.add(um.getId());
				}
				if (idls == null || idls.size() == 0) {
					idls = UserDb.selectAdminIDs();
				}
				String commitDataIDs = StringUtil.mergeListIntegerToString(idls, ",");		
				clienteleInfos = ClienteleDb.selectClienteleInfo(begID, userID, commitDataIDs);
				if (clienteleInfos.size() == 0) {
					begID = 1;
					clienteleInfos = ClienteleDb.selectClienteleInfo(begID, userID, commitDataIDs);
				}
				logger.info("userID: "+userID+" begID: " + begID);
			}			
		}
		
		if (clienteleInfos != null && clienteleInfos.size() > 0) {
			//removeForbidCall(userID, clienteleInfos);	
			//clienteleInfos = removeRepeatInfo(clienteleInfos);
		}
		
		return clienteleInfos;
	}
	
	//  去重  去掉重复的电话号码
	private static List<ClienteleInfoModel> removeRepeatInfo(List<ClienteleInfoModel> clienteleInfos) {
		Set<String> phoneNumSet = new HashSet<String>();
		List<ClienteleInfoModel> noRepeatResult = new ArrayList<ClienteleInfoModel>();
		for (ClienteleInfoModel info : clienteleInfos) {
			String phoneNum = info.getMobi();
			if (phoneNum == null || phoneNum.length() != 11) {
				continue;
			}
			if (!phoneNumSet.contains(phoneNum)) {
				phoneNumSet.add(phoneNum);
				noRepeatResult.add(info);
			}
		}
		
		return noRepeatResult;
	}
	
	private static void removeForbidCall(int userID, List<ClienteleInfoModel> clienteleInfos) {
		if (clienteleInfos == null || clienteleInfos.size() == 0) {
			return;
		}
		
		List<Integer> dispatchIds = new ArrayList<Integer>();		
		Set<String> userCalleeSet = CdrCached.getUserCdrCalleeSet(userID);
			
		Iterator<ClienteleInfoModel> it = clienteleInfos.iterator();
		while (it.hasNext()) {
			ClienteleInfoModel model = it.next();				
			boolean needUpdate = true;
			String curMobi = model.getMobi();
			//if (Config.mobiPhoneEncrypt) {
				//curMobi = PhoneNumDecode.decryptPhone(curMobi);
			//}
			//  去掉  禁止呼叫的号码
			if (allForbidCallee != null && allForbidCallee.size() > 0) {					
				for (String forbidMobi : allForbidCallee) {						
					if (curMobi != null && curMobi.equals(forbidMobi)) {
						it.remove();
						needUpdate = false;
						break;
					}
				}
			}
			//  去掉已经拨打过的号码				
			if (userCalleeSet != null && userCalleeSet.size() > 0) {
				for (String cdrCallee : userCalleeSet) {
					if (curMobi != null && curMobi.equals(cdrCallee)) {
						it.remove();
						needUpdate = false;
						break;
					}
				}
			}
			if (needUpdate) {
				dispatchIds.add(model.getId());
			}
		}
		if (dispatchIds.size() > 0) {
			String strIds = StringUtil.mergeListIntegerToString(dispatchIds, ",");
			ClienteleDb.updateDispatchedUserID(userID, strIds);
		}
	}	
	
	public static int addClienteleModel(List<ClienteleInfoModel> cliModels) {		
		int insertNum = 0;
		try {
			for (int idx = 0; idx < cliModels.size(); ++idx) {
				ClienteleInfoModel model = cliModels.get(idx);
				Integer id = ClienteleDb.insertClienteleObj(model, false);
				if (id != null) {
					insertNum++;
				}
			}
			MybatisManager.commit();
		}
		catch (Exception e) {
			errorLog.error("", e);
		}
		
		return insertNum;
	}
	
	private static List<ClienteleInfoModel> getGroupCallMobiPhone(UserModel user) {
		int companyID = user.getBelongCompanyID();
		ClienteleDb.updateDispenseNoCallByUserID( user.getId() );
		List<String> mobils = ClienteleDb.selectNotCallMobiPhone(companyID);
		if (mobils == null || mobils.size() == 0) {
			groupCallTypeMap.put(companyID, false);
			return null;
		}
		List<ClienteleInfoModel> resultls = new ArrayList<ClienteleInfoModel>();
		StringBuffer strBuf = new StringBuffer();
		for (String mobi : mobils) {
			ClienteleInfoModel clientInfo = new ClienteleInfoModel();
			clientInfo.setMobi(mobi);
			resultls.add(clientInfo);
			if (strBuf.length() > 0) {
				strBuf.append(",");
			}
			strBuf.append("'").append(mobi).append("'");
		}
		
		String strMobils = strBuf.toString();
		ClienteleDb.updateGroupCallDispenseUserid(strMobils, user.getId());
		
		return resultls;
	}
	
	//  获取自有客户
	private static List<ClienteleInfoModel> getMyselfClientleInfo(UserModel user) {
		int userID = user.getId();
		List<ClienteleInfoModel> clienteleInfos = null;
		clienteleInfos = MyselfClienteleDb.selectClienteleInfoByCreateUser(userID);
		int leaderID = user.getLeaderID();
		if ( (clienteleInfos == null || clienteleInfos.size() == 0)
				&& leaderID > 0) {
			clienteleInfos = MyselfClienteleDb.selectClienteleInfoByCreateUser(leaderID);
		}
		
		return clienteleInfos;
	}
	
	
}
